package com.itheima.aop;


import com.itheima.domain.pojo.OperateLog;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.itheima.anno.OperationLog)")
    public Object Around(ProceedingJoinPoint pjp) throws Throwable{
        log.info("环绕通知，开始记录日志：");
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        //创建日志对象
        OperateLog operateLog = new OperateLog();
        //获取当前登录用户id（ThreadLocal办法）
        Integer currentEmpId = UserContext.getCurrentEmpId();
        log.info("当前操作员工号：{}",Thread.currentThread().getName());
        operateLog.setOperateEmpId(currentEmpId);
        //操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        //目标对象的全类名
        String className = pjp.getTarget().getClass().getName();
        operateLog.setClassName(className);//目标对象的的全类名
        //目标方法名
        String methodName = pjp.getSignature().getName();
        operateLog.setMethodName(methodName);
        Object[] args = pjp.getArgs();
        operateLog.setMethodParams(Arrays.toString(args));//目标方法的参数
        operateLog.setReturnValue(pjp.proceed().toString());
        operateLog.setCostTime(end- start);




        //保存日志到数据库表
        operateLogMapper.insert(operateLog);
        return result;

}
}
